package com.ctgu.project03.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.ctgu.project03.response.GetUserDTO;
import com.ctgu.project03.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RefreshTokenInterceptor
 * @Author Alex2
 * @Date 2025/2/26 14:49
 **/
@Component
public class RefreshTokenInterceptor implements HandlerInterceptor {

    @Qualifier("redisTemplateForObject")
    private final RedisTemplate<String, Object> redisTemplateForObject;

    @Autowired
    public RefreshTokenInterceptor(RedisTemplate<String, Object> redisTemplateForObject) {
        this.redisTemplateForObject = redisTemplateForObject;
    }

    private final String REDIS_KEY_LOGIN_TOKEN = "login:token:";

    // 这里只对 redis 方法进行了拦截，并没有拦截 session 方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        System.out.println("url : " + request.getRequestURI() + " - token : " + token + " - Method : " + request.getMethod());
        // token为空时，放行无需登录的请求
        if (token == null || token.isEmpty()) {
            return true;
        }
        Map<Object, Object> userMap = redisTemplateForObject.opsForHash().entries(REDIS_KEY_LOGIN_TOKEN + token);
        if (userMap.isEmpty()) {
            return true;
        }
        GetUserDTO getUserDTO = BeanUtil.fillBeanWithMap(userMap, new GetUserDTO(), false);
        // 保存用户信息到 ThreadLocal
        BaseContext.set(getUserDTO);
        // 请求头中有token，且在redis中命中，则刷新token有效期
        redisTemplateForObject.expire(REDIS_KEY_LOGIN_TOKEN + token, 30, TimeUnit.MINUTES);
        return true;
    }
}